<script setup>
import { ref, onMounted, computed, watchEffect, reactive, watch } from 'vue';
import axios from 'axios';
import config from '../../config.js';
import { useRouter } from 'vue-router';

// 股票列表数据
const stocks = ref([]);
// 分页数据 - 使用响应式对象简化管理
const pagination = reactive({
  page: 0,
  size: 10,
  totalElements: 0,
  totalPages: 0
});

// 初始化时的日志
console.log('初始分页设置:', { size: pagination.size });

// 监控size变化
watch(() => pagination.size, (newSize, oldSize) => {
  console.log('分页大小变更:', { oldSize, newSize });
  // 重置到第一页
  pagination.page = 0;
  loadStocks();
});

// 确保size始终为有效数字
const safeSize = computed(() => {
  const num = Number(pagination.size);
  const result = isNaN(num) ? 10 : Math.max(5, Math.min(num, 50));
  console.log('safeSize计算:', { input: pagination.size, output: result, isNaN: isNaN(num) });
  return result;
});

// 确保totalPages始终为有效数字且大于0
const safeTotalPages = computed(() => {
  const num = Number(pagination.totalPages);
  const result = isNaN(num) ? 1 : Math.max(1, Math.floor(num));
  console.log('safeTotalPages计算:', { input: pagination.totalPages, output: result });
  return result;
});

// 确保page始终为有效数字
const safePage = computed(() => {
  const num = Number(pagination.page);
  const result = isNaN(num) ? 0 : Math.max(0, Math.min(num, safeTotalPages.value - 1));
  return result;
});

// 监控分页变化，确保始终有效
watchEffect(() => {
  // 确保totalElements是有效数字
  if (isNaN(Number(pagination.totalElements))) {
    pagination.totalElements = 0;
    console.warn('totalElements不是有效数字，已重置为0');
  }

  // 确保totalPages是有效数字
  if (isNaN(Number(pagination.totalPages))) {
    pagination.totalPages = 0;
    console.warn('totalPages不是有效数字，已重置为0');
  }

  // 确保页码在有效范围内
  if (pagination.page < 0) pagination.page = 0;
  if (pagination.page >= safeTotalPages.value) {
    pagination.page = Math.max(0, safeTotalPages.value - 1);
  }
});

// 添加额外的调试日志，监控分页组件显示条件
watchEffect(() => {
  console.log('分页组件显示条件:', {
    safeTotalPages: safeTotalPages.value,
    condition: safeTotalPages.value > 0
  });
});

// 添加调试日志，监控分页参数
watchEffect(() => {
  console.log('分页参数监控:', {
    page: pagination.page,
    size: pagination.size,
    totalPages: pagination.totalPages,
    safePage: safePage.value,
    safeSize: safeSize.value
  });
});

// 确保size始终为有效数字
// 此定义已移至上方
// 加载状态
const loading = ref(false);
// 错误信息
const error = ref('');
const router = useRouter();

// 组件挂载时加载数据
onMounted(() => {
  loadStocks();
});

// 加载股票列表
const loadStocks = async () => {
  loading.value = true;
  error.value = '';

  try {
    // 使用安全的分页参数
    console.log('请求分页数据:', { page: safePage.value, size: safeSize.value });
    const response = await axios.get(`${config.api.baseUrl}/api/stocks/page?page=${safePage.value}&size=${safeSize.value}`);
    stocks.value = response.data.content || [];
    pagination.totalElements = Number(response.data.totalElements) || 0;
    pagination.totalPages = Number(response.data.totalPages) || 0;
    console.log('股票列表加载成功:', { content: stocks.value.length, totalElements: pagination.totalElements, totalPages: pagination.totalPages });
  } catch (err) {
    error.value = '加载股票列表失败: ' + (err.response?.data?.error || err.message);
    console.error('加载股票列表失败:', err);
    // 出错时重置分页数据
    pagination.totalElements = 0;
    pagination.totalPages = 0;
  } finally {
    loading.value = false;
  }
};

// 页码变化
const onPageChange = (newPage) => {
  // 确保新页码为有效数字
  const num = Number(newPage);
  pagination.page = isNaN(num) ? 0 : num;
  loadStocks();
};

// 每页条数变化处理函数
const onSizeChange = () => {
  // 这里不需要额外处理，因为watch已经监控了pagination.size的变化
  console.log('分页大小变更触发:', pagination.size);
};


// 跳转到新增页面
const goToAddStock = () => {
  router.push('/stocks/new');
};

// 跳转到编辑页面
const goToEditStock = (id) => {
  router.push(`/stocks/${id}/edit`);
}

// 跳转到导入页面
const goToImportStock = () => {
  router.push('/stocks/import');
};

// 返回首页
const goToHome = () => {
  router.push('/');
}

// 删除股票
const deleteStock = async (id) => {
  if (confirm('确定要删除这支股票吗？')) {
    loading.value = true;
    error.value = '';

    try {
      await axios.delete(`${config.api.baseUrl}/api/stocks/${id}`);
      // 重新加载股票列表
      loadStocks();
    } catch (err) {
      error.value = '删除股票失败: ' + (err.response?.data?.error || err.message);
      console.error('删除股票失败:', err);
    } finally {
      loading.value = false;
    }
  }
};

// 调试分页数据
const debugPagination = () => {
  console.log('手动调试分页数据:');
  console.log('totalElements:', pagination.totalElements, '类型:', typeof pagination.totalElements);
  console.log('totalPages:', pagination.totalPages, '类型:', typeof pagination.totalPages);
  console.log('safeTotalPages:', safeTotalPages.value, '类型:', typeof safeTotalPages.value);
  console.log('safeSize:', safeSize.value, '类型:', typeof safeSize.value);
  console.log('safePage:', safePage.value, '类型:', typeof safePage.value);
  alert(`调试信息:\ntotalElements: ${pagination.totalElements}\ntotalPages: ${pagination.totalPages}\nsafeTotalPages: ${safeTotalPages.value}\nsafeSize: ${safeSize.value}\nsafePage: ${safePage.value}`);
};
</script>

<template>
  <div class="stock-list-container">
    <h1>股票信息管理</h1>

    <div class="action-buttons">
      <button @click="goToAddStock" :disabled="loading">新增股票</button>
      <button @click="goToImportStock" :disabled="loading">导入CSV</button>
      <button @click="loadStocks" :disabled="loading">刷新列表</button>
      <button @click="debugPagination" :disabled="loading">调试分页</button>
      <button @click="goToHome">返回首页</button>
    </div>

    <div v-if="error" class="error-message">{{ error }}</div>

    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <span>加载中...</span>
    </div>

    <table v-else-if="stocks.length > 0" class="stock-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>股票名称</th>
          <th>股票代码</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="stock in stocks" :key="stock.id">
          <td>{{ stock.id }}</td>
          <td>{{ stock.name }}</td>
          <td>{{ stock.code }}</td>
          <td class="actions">
            <button @click="goToEditStock(stock.id)">编辑</button>
            <button @click="deleteStock(stock.id)" class="delete-btn">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <div v-else class="no-data">暂无股票数据</div>

    <!-- 分页组件 - 强制显示 -->
    <div class="pagination-container">
      <div class="debug-info">
        调试信息: totalElements={{pagination.totalElements}} ({{typeof pagination.totalElements}}), totalPages={{pagination.totalPages}} ({{typeof pagination.totalPages}}), safeTotalPages={{safeTotalPages}} ({{typeof safeTotalPages}})
      </div>
      <div class="pagination-info">
        共 {{ pagination.totalElements }} 条记录，每页显示 {{ safeSize }} 条，共 {{ safeTotalPages }} 页
      </div>
      <div class="pagination-controls">
        <button @click="onPageChange(0)" :disabled="loading || safePage === 0">首页</button>
        <button @click="onPageChange(safePage - 1)" :disabled="loading || safePage === 0">上一页</button>
        <span class="page-number">{{ safePage + 1 }} / {{ safeTotalPages }}</span>
        <button @click="onPageChange(safePage + 1)" :disabled="loading || safePage >= safeTotalPages - 1">下一页</button>
        <button @click="onPageChange(safeTotalPages - 1)" :disabled="loading || safePage >= safeTotalPages - 1">末页</button>
        <select v-model="pagination.size" @change="onSizeChange" :disabled="loading" class="pagination-select">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>
  </div>
</template>

<style scoped>
.stock-list-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  color: #333;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  margin-bottom: 15px;
}

.action-buttons button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.action-buttons button:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.error-message {
  color: #e74c3c;
  padding: 10px;
  background-color: #fadbd8;
  border-radius: 4px;
  margin-bottom: 15px;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #09f;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.stock-table {
  width: 100%;
  border-collapse: collapse;
}

.stock-table th, .stock-table td {
  padding: 12px 15px;
  border: 1px solid #ddd;
  text-align: left;
}

.stock-table th {
  background-color: #f2f2f2;
  font-weight: bold;
}

.stock-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.stock-table tr:hover {
  background-color: #f5f5f5;
}

.actions {
  display: flex;
  gap: 8px;
}

.actions button {
  padding: 6px 12px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.actions .delete-btn {
  background-color: #e74c3c;
}

.no-data {
  text-align: center;
  color: #666;
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  color: #666;
}

.debug-info {
  margin-bottom: 10px;
  padding: 5px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 100%;
  text-align: center;
}

.pagination-info {
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-controls button {
  padding: 6px 12px;
  background-color: #f2f2f2;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-controls button:disabled {
  background-color: #f9f9f9;
  color: #999;
  cursor: not-allowed;
}

.pagination-controls .page-number {
  min-width: 40px;
  text-align: center;
}

.pagination-controls select {
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>